<?php
/**
 * <i>date_format</i>定义
 * 
 * @version $Id: IMintDateFormatModifier.php 312 2008-04-23 16:29:38Z iwind $
 * @package util.mint.modifier
 * @since 0.0.2
 */
class IMintDateFormatModifier extends IAbstractMintModifier {
	/**
	 * 构造器
	 *
	 */	
	public function __construct() {
		
	}
	
	/**
	 * 执行
	 *
	 * 这里的实现借鉴了smarty 2.6.18的modifier.date_format插件
	 * 
	 * @return scalar
	 */
	public function execute(/** $format, $defaultDate **/) {
		$arguments = $this->getArguments();
		$variable = $this->getVariable();
		$format = (isset($arguments[0]))?$arguments[0]:"%b %e, %Y";
		$defaultDate = (isset($arguments[1]))?$arguments[1]:"";
			
		if ($variable != "") {
       	 	$timestamp = $this->getTime($variable);
    	} elseif ($defaultDate != "") {
        	$timestamp = $this->getTime($defaultDate);
   	 	} else {
        	return;
    	}
    	if (DIRECTORY_SEPARATOR == '\\') {//windows
       	 	$winFrom = array('%D', '%h', '%n', '%r', '%R',  '%t', '%T');
        	$winTo   = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
	        if (strpos($format, '%e') !== false) {
	            $winFrom[] = '%e';
	            $winTo[] = sprintf('%\' 2d', date('j', $timestamp));
	        }
	        if (strpos($format, '%l') !== false) {
	            $winFrom[] = '%l';
	            $winTo[]   = sprintf('%\' 2d', date('h', $timestamp));
	        }
	        $format = str_replace($winFrom, $winTo, $format);
    	}
    	return strftime($format, $timestamp);
	}
	
	private function getTime($string) {
    	if(empty($string)) {
        	// use "now":
        	$time = time();

	    } elseif (preg_match('/^\d{14}$/', $string)) {
	        // it is mysql timestamp format of YYYYMMDDHHMMSS?            
	        $time = mktime(substr($string, 8, 2),substr($string, 10, 2),substr($string, 12, 2),
	                       substr($string, 4, 2),substr($string, 6, 2),substr($string, 0, 4));
	        
	    } elseif (is_numeric($string)) {
	        // it is a numeric string, we handle it as timestamp
	        $time = (int)$string;
	        
	    } else {
	        // strtotime should handle it
	        $time = strtotime($string);
	        if ($time == -1 || $time === false) {
	            // strtotime() was not able to parse $string, use "now":
	            $time = time();
	        }
	    }
	    return $time;
	}
}

?>